<?php
class Application_Model_Event extends App_DbTable
{
	public function __construct($id = null){
		parent::__construct(new Application_Model_DbTable_Event(), $id);
	}
	
	public function getAll($pagination = false, $currPage = 1, $checkStatus = true, $checkVisible = true){
	$select = $this->_dbTable->select();
		if($checkStatus){
			$select->where('status = ?', 'opened');
		}
		if($checkVisible){
			$select->where('visible = ?', 1);
		}
		$select->order('date_start DESC');
		if($pagination){
	       	$paginator = Zend_Paginator::factory($select);
			$paginator->setItemCountPerPage(10);
	        $paginator->setPageRange(3);
	       	$paginator->setCurrentPageNumber($currPage);         
			return $paginator;
		}
		else{
			return $this->_dbTable->fetchAll($select);
		}
	}
	public function CheckDate(){
    	$date_now = new Zend_Date();
    	$date = new Zend_Date($this->_row->date_close);
    	if($date->compare($date_now) == -1){
    		return false;
    	}
    	else{
    		return true;
    	}
    }
	public function getTeamL(){
		return $this->_row->findParentRow('Application_Model_DbTable_Team', 'Team_Left' );
	}
	public function getTeamR(){
		return $this->_row->findParentRow('Application_Model_DbTable_Team', 'Team_Right' );
	}
	public function getBets(){
		$bets = array();
		$rowset = $this->_row->findDependentRowset('Application_Model_DbTable_Bet', 'Event');
		foreach ($rowset as $row){
			$bets[] = new Application_Model_Bet($row->id);
		}
		return $bets;
	}
	public function recountEvent(){
		if($this->_row->score_left > $this->_row->score_right){
    		$this->_row->result = 'left';
    	}
    	elseif($this->_row->score_left < $this->_row->score_right){
    		$this->_row->result = 'right';
    	}
    	else{
    		$this->_row->result = 'draw';
    	}
    	$this->save();
    	$bets = $this->getBets();
    	foreach ($bets as $bet){
    		$bet->recountBet();  		
    	}  
	}
}